package com.lagou.demo3;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.Trigger;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.api.windowing.windows.Window;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;


/*
基于时间驱动
 */

public class TimeWindowDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1、添加数据源
        DataStreamSource<String> data = env.addSource(new SourceFunction<String>() {
            int count = 0;

            @Override
            public void run(SourceContext<String> ctx) throws Exception {
                while (true) {
                    ctx.collect(count + "数据源");
                    count++;
                    Thread.sleep(1000);
                }
            }
            @Override
            public void cancel() {

            }
        });

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

        //2、转换数据
        SingleOutputStreamOperator<Tuple3<String, String, Integer>> maped = data.map(new MapFunction<String, Tuple3<String, String, Integer>>() {
            @Override
            public Tuple3<String, String, Integer> map(String value) throws Exception {
                //获取系统当前时间
                long l = System.currentTimeMillis();
                String dataTime = sdf.format(l);
                Random random = new Random();
                int randomNum = random.nextInt(5);

                return new Tuple3<>(value, dataTime, randomNum);
            }
        });


        //3、分组
        KeyedStream<Tuple3<String, String, Integer>, String> keyed = maped.keyBy(value -> value.f0);

        //4、获取窗口
        //timeWindow实际上是对TumblingWindows做好了封装，根据EventTime、ProcessingTime返回不同的TumblingWindows窗口
        WindowedStream<Tuple3<String, String, Integer>, String, TimeWindow> timeWindow = keyed.timeWindow(Time.seconds(5));

        //5、操作窗口数据

        SingleOutputStreamOperator<String> applyed = timeWindow.apply(new WindowFunction<Tuple3<String, String, Integer>, String, String, TimeWindow>() {

            //apply对窗口中的每一条数据进行处理
            @Override
            public void apply(String s, TimeWindow window, Iterable<Tuple3<String, String, Integer>> input, Collector<String> out) throws Exception {
                String key = s;
                StringBuilder sb = new StringBuilder();
                Iterator<Tuple3<String, String, Integer>> iterator = input.iterator();
                while (iterator.hasNext()) {
                    Tuple3<String, String, Integer> next = iterator.next();
                    sb.append(next.f0 + "..." + next.f1 + "..." + next.f2);
                }
                String s1 = s + "..." + sdf.format(window.getStart()) + "..." + sdf.format(window.getEnd()) + "..." + sb;
                out.collect(s1);

            }
        });

        //6、输出窗口数据
        // 由于设置了窗口时间为5秒，从打印台可以看到数据5秒中输出一次
        applyed.print();
        env.execute();
    }
}
